package com.example.bluetoothttss;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BtsActivity extends AppCompatActivity {

    public static final String TAG = "BtsActivity";

    public static final int REQUEST_BLE_OPEN = 1;

    private ListView listView;
    private Button btnReturnHome;

    private List<BluetoothDevice> list;

    private BtAdapter btAdapter;

    private BluetoothAdapter mBluetoothAdapter;

    //BluetoothDevice：远程蓝牙设备的一个描述，通过它可以和本地蓝牙设备---BluetoothAdapter连接通信
    private BluetoothDevice bluetoothDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bts);
        isSupportBle();//当前设备是否支持蓝牙

        bindView();//控件

        initData();//数据

        initView();//展示数据

        registerBluetoothReceiver();//注册广播-添加

        requestPermissions();//请求权限
        Button returnBut = findViewById(R.id.btn_return_home);
        returnBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent re = new Intent(BtsActivity.this, MainActivity.class);
                startActivity(re);
            }
        });

//        beDiscovered();//可以被找到

    }


    /**
     * Android 6.0 动态申请授权定位信息权限，否则扫描蓝牙列表为空
     */
    private void requestPermissions() {
        List<String> list = new ArrayList<>();
        // Android 6.0动态请求权限

        // Android 版本小于 Android12 及以下版本
        list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        list.add(Manifest.permission.ACCESS_FINE_LOCATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 版本大于等于 Android12 时
            // 只包括蓝牙这部分的权限，其余的需要什么权限自己添加
            list.add(Manifest.permission.BLUETOOTH_SCAN);
            list.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            list.add(Manifest.permission.BLUETOOTH_CONNECT);
        }

        String[] permissions = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            permissions[i] = list.get(i);
        }
        List<String> requestList = new ArrayList<>();

        for (String str : permissions) {
            if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                requestList.add(str);
            }
        }
        if (requestList.isEmpty()) {
            startDiscovery();
        } else {
            String[] requests = new String[requestList.size()];
            for (int i = 0; i < requestList.size(); i++) {
                requests[i] = requestList.get(i);
            }
            requestPermissions(requests, 111);
        }


    }

    //权限回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.i(TAG, "requestCode:" + requestCode + " ;permissions:" + Arrays.toString(permissions) + "  ;grantResults:" + Arrays.toString(grantResults));
        if (requestCode == 111) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //用户授权
                startDiscovery();
            } else {
                Toast.makeText(BtsActivity.this, "权限申请失败，无法正常使用功能", Toast.LENGTH_SHORT).show();
            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    private void registerBluetoothReceiver() {
        //创建意图过滤器，只处理认定的广播
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//蓝牙扫描是，扫描到任一远程蓝牙设备时，会发送此广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//蓝牙扫描过程结束
        //注册接收器，注册之后才能正常接收广播
        registerReceiver(bluetoothReceiver, filter);
    }

    private void isSupportBle() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//得到本地默认的蓝牙适配器，若为null则表示本地不支持蓝牙

        BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

        mBluetoothAdapter = manager.getAdapter();

        if (mBluetoothAdapter == null || !getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
            showNotSupportBluetoothDialog();//提示框
            Log.e(TAG, "not support bluetooth");
        } else {
            Log.e(TAG, " support bluetooth");

        }
    }

    private void startDiscovery() {//扫描蓝牙设备
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.startDiscovery();//开始查找
        } else {//当发现蓝牙功能未启用时，开启蓝牙功能
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//请求用户是否打开蓝牙
            startActivityForResult(intent, REQUEST_BLE_OPEN);
        }
    }


    //弹窗提示
    private void showNotSupportBluetoothDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("当前设备不支持蓝牙").create();
        dialog.show();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });

    }

    private void showNoBluetoothSupportDialog() {
        // 显示设备不支持蓝牙功能的对话框
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("设备不支持蓝牙")
                .setMessage("您的设备似乎不支持蓝牙功能，请确认后再试。")
                .setPositiveButton("确定", (dialogInterface, i) -> finish())
                .create();
        dialog.show();
    }
    private void initData() {
        list = new ArrayList<>();//空数组
        btAdapter = new BtAdapter(this, list);//创建适配器
    }

    private void bindView() {
        listView = findViewById(R.id.listView);
    }

    private void initView() {
        listView.setAdapter(btAdapter);//绑定适配器
        //每行点击事件，监听哪一行被选中
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                bluetoothDevice = list.get(position);
                Toast.makeText(BtsActivity.this, "连接中", Toast.LENGTH_SHORT).show();
                BtUtils.getInstance().connect(bluetoothDevice);

            }
        });

        BtUtils.getInstance().setOnConnectListener(new OnConnectListener() {
            @Override
            public void onConnect(boolean isConnect) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isConnect) {
                            mBluetoothAdapter.cancelDiscovery();//取消扫描过程
                            Toast.makeText(BtsActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(BtsActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                mBluetoothAdapter.startDiscovery();
            }
        }
    }

    //广播接收
    BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(BluetoothDevice.ACTION_FOUND)) {//搜索发现设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (!TextUtils.isEmpty(device.getName())) {
                    list.add(device);
                    Log.e(TAG, "discovery:" + device.getName());
                    btAdapter.notifyDataSetChanged();//适配器刷新控件
                }
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {//扫描过程结束
                // Toast.makeText(MainActivity.this, "discovery finished", Toast.LENGTH_LONG).show();
                mBluetoothAdapter.cancelDiscovery();//取消查找蓝牙设备
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        BtUtils.getInstance().setOnConnectListener(null);
        unregisterReceiver(bluetoothReceiver);//取消广播
    }

    /**
     * 设置蓝牙可以被其他设备搜索到
     */
    private void beDiscovered() {//如果发现当前设备没有打开对外可见模式，则传递Intent来调用打开可发现模式
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
            startActivity(discoverableIntent);
        }
    }


}